import Snake from "./Snake";
import Food from "./Food";
import ScorePanel from "./ScorePanel";

export default class GameController {
  snake: Snake;
  food: Food;
  scorePanel: ScorePanel;

  direction: string = '';
  isLive: boolean = false;

  constructor() {
    this.snake = new Snake();
    this.food = new Food()
    this.scorePanel = new ScorePanel()

    this.init()
  }

  init() {
    // 绑定键盘事件
    document.addEventListener('keydown', this.handleKeydown.bind(this))
    // document.addEventListener('keydown', (event) => this.handleKeydown(event))
    this.run()
  }

  handleKeydown(event: KeyboardEvent) {
    console.log('handle keydown', event.key)
    // handle keydown ArrowUp
    // handle keydown ArrowRight
    // handle keydown ArrowDown
    // handle keydown ArrowLeft
    if (['ArrowUp', 'ArrowRight', 'ArrowDown', 'ArrowLeft'].indexOf(event.key) > -1) {
      this.direction = event.key;
    }
    
  }

  run() {
    /**
     * 向上  top 减少
     * 向下  top 增加
     * 向左  left 减少
     * 向右  left 增加
     */

    //获取蛇现在的坐标
    let curX = this.snake.X;
    let curY = this.snake.Y;

    switch (this.direction){
      case 'ArrowUp':
        curY -= 10;
        break;
      case 'ArrowDown':
        curY += 10;
        break;
      case 'ArrowLeft':
        curX -= 10;
        break;
      case 'ArrowRight':
        curX += 10;
        break;
    }

    this.checkEat(curX, curY)
    try {
      this.snake.X = curX;
      this.snake.Y = curY;
      this.isLive = true;
    } catch (error) {
      this.isLive = false;
      alert(error);
    }


    this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30)
  }

  // 吃食物
  checkEat(x: number, y: number) {
    if (x == this.food.X && y == this.food.Y) {
      this.food.changePos();
      this.scorePanel.addScore();
      this.snake.addBody()
    }
  } 
}